package com.xuyuan.protocol;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

public class MyCustomProtocolConverter extends AbstractHttpMessageConverter<MyCustomProtocol> {

    public MyCustomProtocolConverter() {
        super(new MediaType("application", "x-custom-protocol"));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return MyCustomProtocol.class.isAssignableFrom(clazz);
    }

    @Override
    protected MyCustomProtocol readInternal(Class<? extends MyCustomProtocol> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputMessage.getBody(), StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String data = sb.toString();
        // 假设数据格式为 "type=1,content=Hello"
        String[] parts = data.split(",");
        MyCustomProtocol protocol = new MyCustomProtocol();
        protocol.setType(Integer.parseInt(parts[0].split("=")[1]));
        protocol.setContent(parts[1].split("=")[1]);
        return protocol;
    }

    @Override
    protected void writeInternal(MyCustomProtocol myCustomProtocol, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), StandardCharsets.UTF_8);
        writer.write("type=" + myCustomProtocol.getType() + ",content=" + myCustomProtocol.getContent());
        writer.flush();
    }
}
